﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UTSDAL.LINQSQL.Views;
using UTSDAL.LINQSQL.DAO;
using UTSDAL.LINQSQL.Model;
using log4net;
using DayPilot.Web.Ui;
using UTS.Controls;
using System.IO;

public partial class pages_admin_scheduling : System.Web.UI.Page
{

    private static readonly ILog log = LogManager.GetLogger(typeof(pages_admin_scheduling));

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["TimetableEvent"] != null)
        {
            this.selectedTimetableEvent = (TimetableEvent)Session["TimetableEvent"];
            SemesterListDropDown.Semester = this.selectedTimetableEvent.Semester;
            CohortDropDownList.Cohort = this.selectedTimetableEvent.Cohort;
            ModuleDropDownList.Module = this.selectedTimetableEvent.Module;
        }

        Session.Remove("TimetableEvent");

                 
        LoadTimetableEvents();


        String message = (String)Session["Message"];
        
        if (message !=null)
        {
            Message.Visible = true;

            switch (message)
            {

                case "Insert":
                    Message.SuccessMessage = "TimetableEvent has been successfully Inserted ";
                    break;
                case "Update":
                    Message.SuccessMessage = "TimetableEvent has been successfully Updated ";
                    break;
                case "Delete":
                    Message.SuccessMessage = "TimetableEvent has been successfully Deleted ";
                    break;
                case "UpdateFailed":
                    Message.FailureMessage = "Could not Update Timetable Event ";
                    break;

            }

            Session["Message"] = null;
        }

        
        
        
    }

    


    private List<TimetableEventView> views = new List<TimetableEventView>();

    private TimetableEventDAO timetableEventDAO = new TimetableEventDAO();

    private SemesterDAO semesterDAO = new SemesterDAO();

    private Semester selectedSemester = null;

    private Cohort selectedCohort = null;
    
    private void LoadTimetableEvents()
    {
        if (selectedSemester == null)
        {
            selectedSemester = semesterDAO.getCurrentSemester();
        }

        ObjectUtils.initCalendar(EventCalendar);

        EventCalendar.DataStartField = "StartTime";
        EventCalendar.DataEndField = "EndTime";
        EventCalendar.DataTextField = "CalendarDisplayString";
        EventCalendar.DataValueField = "TimetableEventId";

        views = timetableEventDAO.getTimetableEventsViewByCriteria(SemesterListDropDown.Semester, CohortDropDownList.Cohort, ModuleDropDownList.Module);
        EventCalendar.DataSource = views;
        EventCalendar.DataBind();
        
    }


    private CohortDAO cohortDAO = new CohortDAO();

    protected void SemesterOrCohort_Changed(object sender, EventArgs e)
    {
        selectedSemester = semesterDAO.findById(new Guid(SemesterListDropDown.SelectedValue));
        selectedCohort = cohortDAO.findById(new Guid(CohortDropDownList.SelectedValue));
        log.Debug("Selected Semester = " + selectedSemester.SemesterName);
        LoadTimetableEvents();
    }

    protected void Schedule_EventClicked(object sender, EventClickEventArgs e)
    {
        log.Debug("Schedule Event Clicked = "+e.Value);
        ScheduleViewingPanel.Visible = false;
        ScheduleEditingPanel.Visible = true;

        selectedTimetableEvent = timetableEventDAO.findById(new Guid(e.Value));
        TimetableEventScheduleView.ChangeMode(DetailsViewMode.Edit);
        editMode(selectedTimetableEvent);
    }

    private CourseDayDAO courseDayDAO = new CourseDayDAO();

    protected void FreeTime_Clicked(object sender, FreeClickEventArgs e)
    {
        log.Debug("Free Time Clicked =" + e.Start.ToShortTimeString()); 
        ScheduleViewingPanel.Visible = false;
        ScheduleEditingPanel.Visible = true;

        selectedTimetableEvent = new TimetableEvent();
        selectedTimetableEvent.CourseDay = courseDayDAO.findByCourseDayName(e.Start.DayOfWeek.ToString());
        selectedTimetableEvent.StartTime = e.Start.TimeOfDay;

        TimetableEventScheduleView.ChangeMode(DetailsViewMode.Insert);
        editMode(selectedTimetableEvent);

    }


    private TimetableEvent selectedTimetableEvent = null;

    private void editMode(TimetableEvent selectedTimetableEvent)
    {
        List<TimetableEvent> events = new List<TimetableEvent>();
        events.Add(selectedTimetableEvent);
        TimetableEventScheduleView.DataSource = events;
        TimetableEventScheduleView.DataBind();
    }

    protected void TimetableEventScheduleView_DataBound(object sender, EventArgs e)
    {
        log.Debug("TimetableEventScheduleView Mode =" + TimetableEventScheduleView.CurrentMode);

        //selectedTimetableEvent = (TimetableEvent)TimetableEventScheduleView.DataItem;

        RoomDropDownList RoomControl = (RoomDropDownList)TimetableEventScheduleView.FindControl("Room");
        CourseDayDropDownList CourseDayControl = (CourseDayDropDownList)TimetableEventScheduleView.FindControl("CourseDay");
        TimeInputControl StartTimeControl = (TimeInputControl)TimetableEventScheduleView.FindControl("StartTime");
        TimeInputControl EndTimeControl = (TimeInputControl)TimetableEventScheduleView.FindControl("EndTime");

        RoomControl.reload();
        CourseDayControl.reload();
        StartTimeControl.TimeValue = selectedTimetableEvent.StartTime;


        if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Edit))
        {
            ViewState["TimetableEventId"] = selectedTimetableEvent.TimetableEventId;
            Literal CohortControl = (Literal)TimetableEventScheduleView.FindControl("Cohort");
            Literal ModuleControl = (Literal)TimetableEventScheduleView.FindControl("Module");
            Literal SemesterControl = (Literal)TimetableEventScheduleView.FindControl("Semester");
            Literal ModuleEventControl = (Literal)TimetableEventScheduleView.FindControl("ModuleEvent");
            

            CohortControl.Text = selectedTimetableEvent.Cohort.CohortName;
            ModuleControl.Text = selectedTimetableEvent.Module.ModuleName;
            SemesterControl.Text = selectedTimetableEvent.Semester.SemesterName;
            ModuleEventControl.Text = selectedTimetableEvent.ModuleEvent.ModuleEventType.ModuleEventTypeName;

            CourseDayControl.SelectedValue = selectedTimetableEvent.CourseDay.CourseDayId.ToString();
            RoomControl.SelectedValue = selectedTimetableEvent.Room.RoomId.ToString();
            log.Debug("Selected Value in Room Control = " + RoomControl.SelectedValue.ToString());

            EndTimeControl.TimeValue = selectedTimetableEvent.EndTime;

            
        }
        else if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Insert))
        {
            
            SemesterDropDownList SemesterDropDownControl = (SemesterDropDownList)TimetableEventScheduleView.FindControl("SemesterDropDownControl");
            SemesterDropDownControl.reload();
            SemesterDropDownControl.Semester = selectedTimetableEvent.Semester;


            CohortDropDownList CohortDropDownControl = (CohortDropDownList)TimetableEventScheduleView.FindControl("CohortDropDownControl");
            CohortDropDownControl.reload();
            CohortDropDownControl.Cohort = selectedTimetableEvent.Cohort;

            ModuleDropDownList ModuleDropDownControl = (ModuleDropDownList)TimetableEventScheduleView.FindControl("ModuleDropDownControl");
            ModuleDropDownControl.reload();
            ModuleDropDownControl.Module = selectedTimetableEvent.Module;

            ModuleEventDropDownList ModuleEventDropDownControl = (ModuleEventDropDownList)TimetableEventScheduleView.FindControl("ModuleEventDropDownControl");
            ModuleEventDropDownControl.reload();
            ModuleEventDropDownControl.ModuleEvent = selectedTimetableEvent.ModuleEvent;


            CourseDayControl.SelectedValue = selectedTimetableEvent.CourseDay.CourseDayId.ToString();
        }
    }

    
    protected void BackButton_Clicked(object sender, EventArgs e)
    {
        this.ScheduleEditingPanel.Visible = false;
        this.ScheduleViewingPanel.Visible = true;
    }


    protected void TimetableEventScheduleView_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Update":
                updateTimetableEvent();
                break;
            case "Delete":
                deleteTimetableEvent();
                break;
            default:
                break;

        }

    }

    private TimetableEventTypeDAO timetableEventTypeDAO = new TimetableEventTypeDAO();


    private void deleteTimetableEvent()
    {
        this.selectedTimetableEvent = timetableEventDAO.findById((Guid)ViewState["TimetableEventId"]);
        timetableEventDAO.remove(this.selectedTimetableEvent);


        this.ScheduleEditingPanel.Visible = false;
        this.ScheduleViewingPanel.Visible = true;

        Session.Add("Message", "Delete");

        // we have to force a page refresh as the AJAX call is not being made !!
        Response.Redirect("~/pages/admin/scheduling.aspx");
        
    }


    private void updateTimetableEvent()
    {
        RoomDropDownList RoomControl = (RoomDropDownList)TimetableEventScheduleView.FindControl("Room");
        CourseDayDropDownList CourseDayControl = (CourseDayDropDownList)TimetableEventScheduleView.FindControl("CourseDay");
        TimeInputControl StartTimeControl = (TimeInputControl)TimetableEventScheduleView.FindControl("StartTime");
        TimeInputControl EndTimeControl = (TimeInputControl)TimetableEventScheduleView.FindControl("EndTime");

        if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Edit))
        {
            this.selectedTimetableEvent = timetableEventDAO.findById((Guid)ViewState["TimetableEventId"]);    
        }
        else if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Insert))
        {
            SemesterDropDownList SemesterDropDownControl = (SemesterDropDownList)TimetableEventScheduleView.FindControl("SemesterDropDownControl");
            CohortDropDownList CohortDropDownControl = (CohortDropDownList)TimetableEventScheduleView.FindControl("CohortDropDownControl");
            ModuleDropDownList ModuleDropDownControl = (ModuleDropDownList)TimetableEventScheduleView.FindControl("ModuleDropDownControl");
            ModuleEventDropDownList ModuleEventDropDownControl = (ModuleEventDropDownList)TimetableEventScheduleView.FindControl("ModuleEventDropDownControl");

            this.selectedTimetableEvent = new TimetableEvent();
            this.selectedTimetableEvent.Semester = SemesterDropDownControl.Semester;
            this.selectedTimetableEvent.Cohort = CohortDropDownControl.Cohort;
            this.selectedTimetableEvent.Module = ModuleDropDownControl.Module;
            this.selectedTimetableEvent.ModuleEvent = ModuleEventDropDownControl.ModuleEvent;
            this.selectedTimetableEvent.Room = RoomControl.SelectedRoom;
            this.selectedTimetableEvent.CourseDay = CourseDayControl.CourseDay;
            

            // We support reservation prior to generation and scheduling after generation through the same interface
            if (semesterDAO.areSemesterTimetablesGenerated(selectedTimetableEvent.Semester))
            {
                this.selectedTimetableEvent.TimetableEventType = timetableEventTypeDAO.getScheduledEventType();
            }
            else
            {
                this.selectedTimetableEvent.TimetableEventType = timetableEventTypeDAO.getReservationEventType();
            }
            
        }

        log.Debug("Updating Timetable Event " + selectedTimetableEvent.StartTime);

        this.selectedTimetableEvent.StartTime = StartTimeControl.TimeValue;
        this.selectedTimetableEvent.EndTime = EndTimeControl.TimeValue;
        this.selectedTimetableEvent.RoomId = new Guid(RoomControl.SelectedValue);


        
            if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Edit))
            {
                
                    timetableEventDAO.save(this.selectedTimetableEvent);
                    log.Debug("Saved!");
                    Session["Message"] = "Update";
                

            }
            else if (TimetableEventScheduleView.CurrentMode.Equals(DetailsViewMode.Insert))
            {
                
                    timetableEventDAO.insert(this.selectedTimetableEvent);
                    log.Debug("Inserted!");
                    Session.Add("Message", "Insert");
                

            }

            Session.Add("TimetableEvent", this.selectedTimetableEvent);
            
            ScheduleViewingPanel.Visible = true;
            ScheduleEditingPanel.Visible = false;

            // we have to force full post back as the AJAX Page Refresh trigger is not being made !!
            Response.Redirect("~/pages/admin/scheduling.aspx");
        }

        



    protected void SemesterDropDownControl_SelectedIndexChanged(object sender, EventArgs e)
    {
        log.Debug("Semester Drop Down Changed ... Refreshing Cohort DropDown");
        

        
        CohortDropDownList.DataSource = cohortDAO.findCohortsBySemester(SemesterListDropDown.Semester);
        CohortDropDownList.DataBind();
        DropDownUtils.addDefaultLabel(CohortDropDownList, "Select a Cohort");
        log.Debug("Refreshed Cohort Drop Down ");

        LoadTimetableEvents();
    
    }

    private ModuleDAO moduleDAO = new ModuleDAO();

    protected void CohortDropDownControl_SelectedIndexChanged(object sender, EventArgs e)
    {

        log.Debug("Cohort Drop Down Changed ");
        ModuleDropDownList.DataSource = moduleDAO.findModulesByCohortAndSemester(CohortDropDownList.Cohort, SemesterListDropDown.Semester);
        ModuleDropDownList.DataBind();
        DropDownUtils.addDefaultLabel(ModuleDropDownList, "Select a Module");
        log.Debug("Cohort Drop Down Changed Complete ");

        LoadTimetableEvents();
    }

    private ModuleEventDAO moduleEventDAO = new ModuleEventDAO();

    protected void ModuleDropDownControl_SelectedIndexChanged(object sender, EventArgs e)
    {
        log.Debug("Module Drop Down Changed ");
        
        LoadTimetableEvents();
    }



    protected void PrintSchedule(object sender, EventArgs e)
    {
        String fileName = "Timetable.html";

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter writer = new HtmlTextWriter(stringWriter);

        EventCalendar.RenderControl(writer);

        log.Debug(stringWriter.ToString());

        Response.Write(Server.MapPath("~/" + fileName));
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(Server.MapPath("~/" + fileName));
        Response.Flush();
        Response.Close();

        
    }
}
